<template>
  <div>
    <el-upload v-if="type === 1 && fileLimit == 1" :action="action" :headers="headers" :on-success="onSuccess" :show-file-list="false" :style="'height:100px; width:100px'" class="avatar-uploader">
      <img v-if="datas" :src="datas" :style="'height:100px; width:100px'" class="avatar">
      <i v-else :style="'height:100px; width:100px'" class="el-icon-plus avatar-uploader-icon small_icon" />
    </el-upload>
    <el-upload
      v-if="type === 1 && fileLimit > 1"
      :action="action"
      :headers="headers"
      :on-progress="onProgress"
      :on-success="onSuccess"
      :on-remove="onRemove"
      :file-list="fileList"
      :limit="fileLimit"
      :class="(fileSize >= fileLimit) ? 'hide': ''"
      multiple
      list-type="picture-card"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-upload
      v-if="type === 2"
      :action="action"
      :headers="headers"
      :on-progress="onProgress"
      :on-success="onSuccess"
      :on-remove="onRemove"
      :on-error="onError"
      :file-list="fileList"
      :limit="fileLimit"
      :on-exceed="handleExceed"
      :before-upload="beforeUpload"
      multiple
      class="upload-demo"
    >
      <el-button size="small" type="primary">{{ btnName }}</el-button>
      <div slot="tip" class="el-upload__tip">不超过200M，音视频只允许上传后缀[.mp3, .wav, .wma, .acc, .mp4]文件</div>
    </el-upload>
    <el-upload
      v-if="type === 3"
      :action="action"
      :headers="headers"
      :on-success="onSuccess"
      :on-remove="onRemove"
      :file-list="fileList"
      :limit="fileLimit"
      :on-exceed="handleExceed"
      drag
      multiple
      class="upload-demo"
    >
      <i class="el-icon-upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
    </el-upload>

  </div>
</template>
<script>
import { getToken } from '@/utils/auth'
import { getUploadUrl } from '@/api/service'

export default {
  model: {
    prop: 'datas',
    event: 'return'
  },
  props: {
    datas: {
      type: [Array, String],
      default: () => null
    },
    type: {
      type: Number,
      default: 1
    },
    limit: {
      type: Number,
      default: 6
    },
    dir: {
      type: String,
      default: null
    },
    local: {
      type: Boolean,
      default: false
    },
    onTime: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      action: getUploadUrl(this.local),
      headers: {
        Code: this.dir,
        Token: getToken()
      },
      fileList: [],
      fileLimit: 6,
      fileSize: 0,
      isLocal: false,
      oldBean: [],
      btnName: '点击上传',
      loading: false
    }
  },
  watch: {
    datas: {
      handler(newValue, oldValue) {
        // console.log('datas', newValue, oldValue, this.oldBean)
        if (JSON.stringify(newValue) !== JSON.stringify(this.oldBean)) {
          this.onInit()
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    if (window.location.hostname === 'localhost') {
      this.isLocal = true
    }
    this.onInit()
  },
  methods: {
    onInit() {
      this.fileList = []
      this.fileLimit = this.limit
      if (this.datas) {
        if (this.datas instanceof Array) {
          for (const data of this.datas) {
            const url = data.file ? data.file.url : data.url
            this.fileList.push({
              id: data.id,
              url: url,
              name: data.key || data.title || url.substring(url.lastIndexOf('/') + 1),
              fileId: data.file ? data.file.id : ''
            })
          }
          this.fileSize = this.fileList.length
        } else {
          this.fileLimit = 1
          if (this.datas) {
            this.fileList.push({
              url: this.datas,
              name: this.datas.substring(this.datas.lastIndexOf('/') + 1)
            })
          }
          this.fileSize = this.fileList.length
        }
      } else {
        this.fileSize = 0
      }
      // console.log('this.fileList', this.fileList)
    },
    onReturn(fileList) {
      let back = []
      if (this.fileLimit > 1) {
        // console.log('fileList===>', fileList)
        for (const file of fileList) {
          // console.log('file===>', JSON.stringify(file))
          if (file.response && file.response.code === 200 && file.response.data) {
            back.push({
              url: this.isLocal || !file.response.data.path ? file.response.data.url : file.response.data.path,
              title: file.key || file.name,
              fileId: file.response.data.id
            })
          } else if (file.id && (file.fileId || file.url)) {
            back.push({
              id: file.id,
              url: file.url,
              title: file.key || file.name,
              fileId: file.fileId
            })
          }
        }
      } else {
        // b
        // console.log('fileList', fileList)
        // 最后一个返回，解决上传多次，第一张总是重复
        const file = fileList.pop()
        // console.log('file', JSON.stringify(file))
        if (file && file.response && file.response.data) {
          back = this.isLocal || !file.response.data.path ? file.response.data.url : file.response.data.path
          this.fileList = []
          this.fileList.push({
            url: back,
            name: back.substring(back.lastIndexOf('/') + 1)
          })
        } else {
          back = ''
        }
      }
      this.oldBean = back
      console.log('back===>', JSON.stringify(back), this.fileSize, this.fileLimit)
      this.$emit('return', back)
    },
    beforeUpload(file) {
      this.loading = true
      this.startTime = new Date().getTime()
      var fileName = file.name || ''
      var ext = fileName.split('.')[fileName.split('.').length - 1]
      if ('png,jpg,bmp,gif,mp3,mp4,flv,xls,pdf,wav,wma,acc,apk'.split(',').findIndex(v => v === ext.toLowerCase()) < 0) {
        this.$message.error('上传资源只能是 png,jpg,bmp,gif,mp3,mp4,flv,xls,pdf,wav,wma,acc,apk 格式!')
        this.loading = false
        return false
      }
      if (parseInt(file.size) > parseInt(200 * 1024 * 1024)) {
        this.$message.error('上传文件上限为200MB')
        this.loading = false
        return false
      }
      // console.log('this.onTime', this.onTime, !!this.onTime)
      if (!!this.onTime && ('mp3,mp4,flv,wav,wma,acc'.split(',').findIndex(v => v === ext.toLowerCase()) > -1)) {
        // 获取视频时长
        var url = URL.createObjectURL(file)
        var audioElement = new Audio(url)
        const timeFun = this.onTime
        audioElement.addEventListener('loadedmetadata', function(_event) {
          const duration = audioElement.duration // 时长为秒，小数，182.36
          // console.log('获取视频时长', duration, timeFun)
          timeFun && timeFun(duration)
        })
      }
    },
    onProgress(event, file, fileList) {
      this.fileSize = fileList.length
      console.log('event', event)
      if (this.percent === 100) {
        // this.btnName = '点击上传'
      }
      this.btnName = '正在上传...' + event.percent + '%，耗时:' + (new Date().getTime() - this.startTime) / 1000 + 's'
    },
    onError(err, file, fileList) {
      this.btnName = '点击上传'
      this.$message.error('上传失败:' + JSON.stringify(err))
    },
    onSuccess(res, file, fileList) {
      console.log('onSuccess', res)
      this.loading = false
      this.btnName = '点击上传'
      if (res && res.code === 200) {
        this.fileSize = fileList.length
        this.onReturn(fileList)
        this.$message({
          type: 'success',
          message: '上传成功'
        })
      } else {
        this.fileSize = fileList.length
        this.onReturn(fileList)
        this.$message.error('上传失败:' + res.msg)
      }
    },
    onRemove(file, fileList) {
      this.fileSize = fileList.length
      this.onReturn(fileList)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 ${this.fileLimit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    randomName(file) {
      return this.randomStr(32) + file.name.substring(file.name.lastIndexOf('.'))
    },
    randomStr(len) {
      len = len || 32
      var chars = 'abcdefhijkmnprstwxyz2345678'
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * chars.length))
      }
      return pwd
    }
  }
}
</script>
<style>
.hide .el-upload--picture-card {
  display: none;
}
.small_icon {
  line-height: 95px;
}
</style>
